package com.tengju.motivation.domain.shared;

import lombok.Getter;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

import static com.tengju.motivation.domain.shared.DateUtil.DATE_FORMAT_MONTH_INT;

@Getter
public class Quarter {

    private String quarter;

    private Date startTime;
    private Date endTime;
    private Date nextQuarterStartTime;
    private Integer firstMonth;
    private Integer secondMonth;
    private Integer lastMonth;

    private List<Integer> yearMonthList;
    private List<String> yearMonthStringList;
    /**
     * 是否第一个月份
     */
    private boolean isFirstMonth;
    /**
     * 是否第二个月份
     */
    private boolean isSecondMonth;
    /**
     * 是否第三个月份
     */
    private boolean isThirdMonth;

    private Quarter() {
    }

    private Quarter(String quarter) {
        this.quarter = quarter;
        startTime = DateUtil.localDateTimeToDate(DateUtil.getQuarterMin(quarter));
        endTime = DateUtil.localDateTimeToDate(DateUtil.getQuarterMax(quarter));
        nextQuarterStartTime = DateUtil.localDateTimeToDate(DateUtil.getNextQuarterMin(quarter));
        yearMonthList = DateUtil.getYearMonthListOfQuarter(quarter);
        yearMonthStringList = DateUtil.getYearMonthStringListOfQuarter(quarter);
        firstMonth = yearMonthList.get(0);
        secondMonth = yearMonthList.get(1);
        lastMonth = yearMonthList.get(2);
    }

    public static Quarter of(String quarter) {
        return new Quarter(quarter);
    }

    public boolean sameQuarter(LocalDateTime localDateTime) {
        long nowTime = DateUtil.localDateTimeToDate(localDateTime).getTime();
        return this.startTime.getTime() <= nowTime && this.endTime.getTime() >= nowTime;
    }

    public boolean sameFirstDay(LocalDateTime localDateTime) {
        return this.startTime.equals(DateUtil.localDateTimeToDate(LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MIN)));
    }

    public boolean isFirstMonth() {
        return isCurrentMonth(firstMonth);
    }

    public boolean isSecondMonth() {
        return isCurrentMonth(secondMonth);
    }

    private boolean isCurrentMonth(Integer secondMonth) {
        long nowTime = DateUtil.getCurrentTime();
        LocalDateTime secondMonthMin = LocalDateTime.of(DateUtil.format(secondMonth + "", DATE_FORMAT_MONTH_INT).toLocalDate(), LocalTime.MIN);
        LocalDateTime secondMonthMax = LocalDateTime.of(DateUtil.format(secondMonth + "", DATE_FORMAT_MONTH_INT).toLocalDate(), LocalTime.MAX);
        return DateUtil.localDateTimeToDate(secondMonthMin).getTime() <= nowTime &&
                DateUtil.localDateTimeToDate(secondMonthMax).getTime() >= nowTime;
    }

    public boolean isThirdMonth() {
        return isCurrentMonth(lastMonth);
    }
}
